"""
myrepos 配置文件生成器
生成 .mrconfig 文件，兼容 myrepos 工具
"""
import os
from pathlib import Path
from config import Config
from i18n import t


class MRConfigGenerator:
    """myrepos 配置文件生成器"""
    
    def __init__(self, config: Config = None):
        """
        初始化生成器
        :param config: 配置对象
        """
        self.config = config or Config()
        self.workspace = Path(self.config.get_workspace())
    
    def _is_repo_initialized(self, repo: str) -> bool:
        """
        检查仓库是否已初始化
        :param repo: 仓库名
        :return: 是否已初始化
        """
        repo_path = self.workspace / repo
        if not repo_path.exists():
            return False
        # 检查是否是 git 仓库
        git_dir = repo_path / ".git"
        return git_dir.exists() or git_dir.is_file()
    
    def generate_mrconfig(self, username: str = None, branch: str = None, repo_list: list = None, only_initialized: bool = False) -> bool:
        """
        生成 .mrconfig 文件
        :param username: GitCode 用户名（如果提供，使用 fork 仓；否则使用主仓）
        :param branch: 分支名（如果提供，使用该分支；否则使用默认分支）
        :param repo_list: 仓库列表（如果提供，只生成这些仓库的配置；否则使用所有仓库）
        :param only_initialized: 如果为 True，只包含已初始化的仓库
        :return: 是否成功
        """
        if not username:
            username = self.config.get_gitcode_username()
        
        if not username:
            print(t("mrconfig.warning_no_username_provided_using_main"))
        
        mrconfig_path = self.workspace / ".mrconfig"
        base_org = self.config.get_base_org()
        target_branch = branch if branch else self.config.get_default_branch()
        
        # 确定要包含的仓库列表
        if repo_list is not None:
            # 如果指定了仓库列表，使用该列表
            repos = repo_list
        elif only_initialized:
            # 如果只包含已初始化的仓库，检查所有配置中的仓库
            all_repos = self.config.get_repos()
            repos = [repo for repo in all_repos if self._is_repo_initialized(repo)]
        else:
            # 否则使用配置中的所有仓库
            repos = self.config.get_repos()
        
        try:
            with open(mrconfig_path, 'w', encoding='utf-8') as f:
                # 写入默认配置
                f.write("# myrepos configuration file\n")
                f.write("# Generated by cjdev tool\n")
                f.write("# This file is compatible with myrepos (mr) command\n\n")
                
                # 为每个仓库生成配置
                for repo in repos:
                    if username:
                        repo_url = f"https://gitcode.com/{username}/{repo}.git"
                        upstream_url = f"https://gitcode.com/{base_org}/{repo}.git"
                    else:
                        repo_url = f"https://gitcode.com/{base_org}/{repo}.git"
                        upstream_url = None
                    
                    f.write(f"[{repo}]\n")
                    f.write(f"checkout = git clone -b {target_branch} --single-branch {repo_url} {repo}\n")
                    f.write(f"update = git pull origin {target_branch}\n")
                    if upstream_url:
                        f.write(f"# Sync from upstream: cd {repo} && git fetch upstream {target_branch} && git merge upstream/{target_branch}\n")
                    f.write(f"status = git status\n")
                    f.write(f"diff = git diff\n")
                    f.write(f"log = git log --oneline -10\n")
                    f.write("\n")
            
            print(t("mrconfig.generated_mrconfig_at_path", path=mrconfig_path))
            return True
        except Exception as e:
            print(t("mrconfig.failed_to_generate_mrconfig_error", error=e))
            return False
    
    def update_mrconfig_branch(self, branch: str) -> bool:
        """
        更新 .mrconfig 文件中的分支信息
        :param branch: 分支名
        :return: 是否成功
        """
        mrconfig_path = self.workspace / ".mrconfig"
        
        if not mrconfig_path.exists():
            # 如果不存在，生成新的
            return self.generate_mrconfig()
        
        try:
            # 读取现有配置
            with open(mrconfig_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # 替换分支信息
            import re
            # 替换 checkout 命令中的分支
            content = re.sub(
                r'checkout = git clone -b \S+',
                f'checkout = git clone -b {branch}',
                content
            )
            # 替换 update 命令中的分支
            content = re.sub(
                r'update = git pull origin \S+',
                f'update = git pull origin {branch}',
                content
            )
            # 替换 upstream sync 注释中的分支
            content = re.sub(
                r'# Sync from upstream: cd \S+ && git fetch upstream \S+ && git merge upstream/\S+',
                lambda m: re.sub(r'upstream/\S+', f'upstream/{branch}', m.group(0)),
                content
            )
            
            # 写回文件
            with open(mrconfig_path, 'w', encoding='utf-8') as f:
                f.write(content)
            
            print(t("mrconfig.updated_mrconfig_branch_to_branch", branch=branch))
            return True
        except Exception as e:
            print(t("mrconfig.failed_to_update_mrconfig_error", error=e))
            return False

